#!/bin/sh

DAEMON="swupdate"
PIDFILE="/var/run/$DAEMON.pid"

LINE=$(cat /proc/cmdline)
VAR=$(echo ${LINE:28:14} | awk '{print $1}')
if [ $VAR =  '/dev/mmcblk1p2' ]; then
	ROOTFS="rootfs-1"
else
	ROOTFS="rootfs-2"
fi

if test -f /update-ok ; then
	SURICATTA_ARGS="-c 2"
	rm -f /update-ok
else
	SURICATTA_ARGS="-c 1"
fi

CID=`cat /sys/devices/soc0/soc/2100000.aips-bus/2194000.usdhc/mmc_host/mmc1/mmc1:0001/cid`
MMCCID=("-i BrImx6ullpro_01-$(echo ${CID:23:9} | awk '{print $1}')")

exec /usr/bin/swupdate-progress -w -r &

start() {
	printf 'Starting %s: ' "$DAEMON"
	# shellcheck disable=SC2086 # we need the word splitting
	start-stop-daemon -b -q -m -S -p "$PIDFILE" -x "/usr/bin/$DAEMON" \
		-- -f /etc/swupdate/swupdate.cfg -L -e rootfs,${ROOTFS} -u "${SURICATTA_ARGS} ${MMCCID}" 
	status=$?
	if [ "$status" -eq 0 ]; then
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

stop() {
	printf 'Stopping %s: ' "$DAEMON"
	start-stop-daemon -K -q -p "$PIDFILE"
	status=$?
	if [ "$status" -eq 0 ]; then
		rm -f "$PIDFILE"
		echo "OK"
	else
		echo "FAIL"
	fi
	return "$status"
}

restart() {
	stop
	sleep 1
	start
}

case "$1" in
        start|stop|restart)
		"$1";;
	reload)
		# Restart, since there is no true "reload" feature.
		restart;;
        *)
                echo "Usage: $0 {start|stop|restart|reload}"
                exit 1
esac
